package interfaces

import (
	"context"
	"net/http"
	"strconv"
	"zxstudy.com/domain/entity"
	"zxstudy.com/application"

	"github.com/gin-gonic/gin"
)

type Groups struct {
	ga application.GroupApplication
}

func NewGroupApplication(ga application.GroupApplication) *Groups {
	return &Groups{
		ga: ga,
	}
}

/**
 * route: /group/
 * method: post
 */
func (g *Groups) Create(c *gin.Context) {
	var group *entity.Group
	if err := c.ShouldBindJSON(&group); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	newGroup, err := g.ga.Create(context.Background(), group)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1, 
			"message": err.Error(),
		})
		return
	}
	
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"group": newGroup,
	})
}

/**
 * route: /group/:id
 * method: get
 */
func (g *Groups) Get(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	group, err := g.ga.Get(context.Background(), id)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"group": group,
	})
}

/**
 * route: /group/
 * method: get
 */
func (g *Groups) Groups(c *gin.Context) {
	groups, err := g.ga.Groups(context.Background())
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"message": groups,
	})
}